﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Threading;

namespace TiebaSignWP7
{
    class TBSGetter
    {
        public TBSGetter(CookieContainer cc)
        {
            this.tcc = cc;
        }
        private CookieContainer tcc = new CookieContainer();
        private string tbsUrl = "http://tieba.baidu.com/dc/common/tbs";
        private string tbs = "";
        private bool isAsyncComplete = false;
        public string paras = "kkkkkkk";

        public string GetTBS()
        {
            //paras = tbsUrl;
            GetPage(tbsUrl);
            while (isAsyncComplete == false)
                ;
            return tbs;
        }

        private void GetPage(string tiebaUrl)
        {
            string url = tiebaUrl;
            //创建WebRequest类
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (tcc == null)
                tcc = new CookieContainer();
            request.CookieContainer = tcc;
            request.Method = "GET";
            //返回异步操作的状态
            IAsyncResult result = (IAsyncResult)request.BeginGetResponse(GetPageResponse, request);
        }

        private void GetPageResponse(IAsyncResult result)
        {
            string webPageContentString = "";
            //获取异步操作返回的的信息
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            //结束对 Internet 资源的异步请求
            WebResponse response = request.EndGetResponse(result);
            //avoid multi-dispose by try finally segment
            Stream strm = null;
            try
            {
                strm = response.GetResponseStream();
                using (StreamReader sreader = new StreamReader(strm))
                {
                    strm = null;
                    webPageContentString = sreader.ReadToEnd();
                    HandlePageException(webPageContentString);
                }
            }
            finally
            {
                if (strm != null)
                    strm.Dispose();
            }
        }

        private void HandlePageException(string webPageContentString)
        {
            if (webPageContentString.Contains("tbs"))
            {
                Regular(webPageContentString);
            }
        }

        private void Regular(string webPageContentString)
        {
            
            string rs = "(tbs\":\")(.*?)(\")";
            Regex r = new Regex(rs, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match m = r.Match(webPageContentString);
            for (; m.Success; m = m.NextMatch())
            {
                tbs = m.Groups[2].ToString();
            }
            isAsyncComplete = true;
        }
    }
}
